import store from "@/common/app/store.js";
import cacheKeys from "@/common/app/cacheKeys.js";

export default {
  /**
   * 判断对象是否是空对象
   * @param {Object || Array} obj 待判断的对象
   * @return {Boolean} 判断结果，true：为空；false：不为空
   */
  isEmpty(obj) {
    if (typeof obj === undefined || obj === null) {
      return true;
    }
    let arr = Object.keys(obj);
    if (arr.length > 0) {
      return false;
    }
    return true;
  },

  /**
   * 通过正则表达式判断字符串是否合法
   * @param {Object} type 字符串类型，如手机号码、邮箱、数字等
   * @param {Object} str 待校验的字符串
   */
  regexp(type, str) {
    let result = false;
    switch (type) {
      // 国内手机号
      case "phone":
        result = /^1\d{10}$/.test(str);
        break;
      // 邮箱
      case "email":
        result = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(str);
        break;
      // 数字
      case "number":
        result = /^[0-9]*$/.test(str);
        break;
      // 短信验证码
      case "code":
        result = /^[0-9]{6}$/.test(str);
        break;
      // 身份证号码
      case "idcard":
        result = /^\d{15}|\d{18}$/.test(str);
        break;
      default:
        break;
    }
    return result;
  },
  /**
   * 根据文件字节数大小，获取文件展示大小，如xxKB，xxMB，xxGB，xxTB
   * @param {Number} size 文件大小，字节数
   */
  formatFileSize(size = 0) {
    let kbSize = size / 1024;
    kbSize = kbSize.toFixed(2);
    if (kbSize < 1024) {
      return kbSize + " KB";
    }
    let mbSize = kbSize / 1024;
    mbSize = mbSize.toFixed(2);
    if (mbSize < 1024) {
      return mbSize + " MB";
    }
    let gbSize = mbSize / 1024;
    gbSize = gbSize.toFixed(2);
    if (gbSize < 1024) {
      return gbSize + " GB";
    }
    let tbSize = gbSize / 1024;
    tbSize = tbSize.toFixed(2);
    if (tbSize < 1024) {
      return tbSize + " TB";
    }
  },
  /**
   * H5页面下载文件
   * @param {String} fileUrl 文件下载地址
   */
  downloadFileForH5(fileUrl) {
    return new Promise((resolve) => {
      let result = {
        success: false,
        message: "下载失败",
      };
      let fileName = fileUrl.substr(fileUrl.lastIndexOf("/") + 1);
      let request = new XMLHttpRequest();
      request.open("GET", fileUrl, true);
      request.responseType = "blob";
      request.onload = function () {
        if (request.readyState === 4 && request.status === 200) {
          let blob = this.response;
          // 转换一个blob链接
          let u = window.URL.createObjectURL(new Blob([blob]));
          let link = document.createElement("a");
          link.download = fileName;
          link.href = u;
          link.style.display = "none";
          document.body.appendChild(link);
          link.click();
          link.remove();
          result = {
            success: true,
            message: "开始下载",
          };
          resolve(result);
        }
      };
      request.send();
    });
  },
  /**
   * 根据秒数获取播放时长字符串，返回如：'01:23:24'（大于1小时）、'34:25'（小于1小时，大于1分钟）、'00:15'（小于1分钟）
   * @param {Number} second 播放时长（单位：秒）
   */
  getDurationText(second = 0) {
    let hours = Math.floor(second / 3600);
    let minutes = Math.floor((second % 3600) / 60);
    let seconds = Math.floor((second % 3600) % 60);
    let timeArr = [];
    if (hours > 0) {
      hours = hours > 9 ? hours : "0" + hours;
      timeArr.push(hours);
    }
    minutes = minutes > 9 ? minutes : "0" + minutes;
    timeArr.push(minutes);
    seconds = seconds > 9 ? seconds : "0" + seconds;
    timeArr.push(seconds);
    return timeArr.join(":");
  },
  /**
   * 获取客户端IP地址
   */
  getLocalIp() {
    let ipAddress = store.getters.clientAddress || "";
    if (!ipAddress || !ipAddress.length) {
      ipAddress = (window.localIpInfo && window.localIpInfo.ip) || "";
      store.commit(cacheKeys.CACHE_CLIENT_ADDRESS, ipAddress);
    }
    return ipAddress || "0.0.0.0";
  },

  /**
   * 获取公共文件中配置的全局系统参数（public/config/index.js中配置的SYSTEM_CONFIG参数），用于页面中使用
   * @returns public/config/index.js中配置的SYSTEM_CONFIG参数
   */
  getSystemConfig() {
    return window.systemConfig.SYSTEM_CONFIG || {};
  },

  /**
   * 解决JS在做数学运算时，出现精度不准确的问题
   * @param {Number} num1 计算的第一个数字
   * @param {Number} num2 计算的第二个数字
   * @param {String} operate 运算符（+、-、*、/）
   * @returns 
   */
  calculate(num1, num2, operate) {
    const numStr1 = String(num1);
    const numStr2 = String(num2);
    let pow1 = 1;
    let pow2 = 1;
    if (numStr1.indexOf(".") !== -1) {
      const decimal1 = numStr1.split(".")[1].length;
      pow1 = Math.pow(10, decimal1);
    }
    if (numStr2.indexOf(".") !== -1) {
      const decimal2 = numStr2.split(".")[1].length;
      pow2 = Math.pow(10, decimal2);
    }
    const pow = Math.max(pow1, pow2);
    switch(operate) {
      case '+':
        return ((num1 * pow) + (num2 * pow)).toFixed(0) / pow;
      case '-':
        return ((num1 * pow) - (num2 * pow)).toFixed(0) / pow;
      case '*':
        return ((num1 * pow).toFixed(0) * (num2 * pow).toFixed(0)) / (pow * pow);
      case '/':
        return ((num1 * pow).toFixed(0) / (num2 * pow).toFixed(0));
      default:
        return 0;
    }
  },
};
